package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.QueryDevicePropertyStatusDTO;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.vo.DeviceDataVO;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient iotDAClient;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     * 
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //1.请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //2.设置条数
        listProductsRequest.setLimit(50);
        //3.发起请求
        ListProductsResponse listProductsResponse = iotDAClient.listProducts(listProductsRequest);
        if (listProductsResponse.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //4.存储到redis
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(listProductsResponse.getProducts()));
    }

    /**
     * 查询所有产品列表
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //1.从redis中获取数据
        String jsonStr = JSONUtil.toJsonStr(redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST));
        //2.如果为空返回一个空集合
        if (StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        //3.解析数据并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }
    /**
     * 注册设备
     * @param dto
     * @return
     */
    @Override
    public boolean registerDevice(DeviceDto dto) {
        //1.判断设备名称是否存在
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (count > 0){
            throw new BaseException("设备名称已存在");
        }
        //2.判断设备标识码是否存在
        count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if (count > 0){
            throw new BaseException("设备标识码已存在");
        }
        //3.判断同一位置是否有相同产品
        count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null,
                Device::getPhysicalLocationType, dto.getPhysicalLocationType()));
        if (count > 0){
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
        //4.注册设备
        //4.1创建AddDeviceRequest和AddDevice对象
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        //4.2秘钥设置
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replace("-","");
        authInfo.setSecret(secret);
        body.withAuthInfo(authInfo);
        request.withBody(body);

        //4.3发起添加请求,接收返回数据是否有异常
        AddDeviceResponse response;
        try {
            response = iotDAClient.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        //5.本地保存设备
        //5.1属性拷贝
        Device device = BeanUtil.toBean(dto, Device.class);
        //5.2秘钥
        device.setSecret(secret);
        //5.3设备id,设备绑定状态
        device.setIotId(response.getDeviceId());
        boolean save = this.save(device);
        return save;
    }

    /**
     * 查询设备详情
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //3.查看本地数据库
        Device device = this.getOne(Wrappers.< Device>lambdaQuery().eq(Device::getIotId, iotId));
        //3.1利用hutool工具判断设备是否为空
        if (ObjectUtil.isEmpty(device)){
            throw new BaseException("设备不存在");
        }
        //2.查询物联网平台IOT
        //2.1创建ShowDeviceRequest
        ShowDeviceRequest request = new ShowDeviceRequest();
        //2.2创建查询参数
        request.setDeviceId(iotId);
        //2.3发起查询请求
        ShowDeviceResponse response = iotDAClient.showDevice(request);
        //2.4判断响应状态是否为200
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        //2.5获取设备状态
        String status = response.getStatus();
        //2.6获取激活时间
        String activeTime = response.getActiveTime();
        //1.封装数据
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //1.1给绑定位置赋值
        vo.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        //1.2给设备状态赋值
        vo.setDeviceStatus(status);
        //1.3转换日期类型
        if (StringUtils.isNotEmpty(activeTime)) {
            LocalDateTime activeTime1 = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            activeTime1 = DateTimeZoneConverter.utcToShanghai(activeTime1);
            vo.setActiveTime(activeTime1);
        }
        return vo;
    }
    /**
     * 查询设备影子数据
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //1.查询Iot平台上的数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = iotDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200){
            throw new BaseException("查询设备影子数据失败");
        }
        //1.1获取上报数据集合
        List<DeviceShadowData> shadowList = response.getShadow();
        if (CollectionUtil.isEmpty(shadowList)) {
            return Collections.emptyList();
        }
        //1.2上报数据的属性对象
        DeviceShadowProperties deviceShadowProperties = shadowList.get(0).getReported();
        //1.3获取属性对象,json对象
        Object properties = deviceShadowProperties.getProperties();
        JSONObject jsonObject = JSONUtil.parseObj(properties);
        //1.4获取设备上报时间
        String eventTimeStr = deviceShadowProperties.getEventTime();
        LocalDateTime eventTimeLocalDateTime  = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        //1.5时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);
        //2.封装数据
        List<Map<String, Object>> list = new ArrayList<>();
        //2.1 遍历属性对象，key表示属性名称，value表示属性值
        jsonObject.forEach((key, value)->{
            Map<String, Object> map=new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 修改设备
     * @param dto
     */
    @Override
    public void editDevice(DeviceDto dto) {
        //1.修改华为云设备
        //1.1查询本地数据库是否有数据
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getId, dto.getId()));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //1.2创建修改设备参数,准备修改华为云设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(dto.getDeviceName());
        request.withBody(body);
        try {
            UpdateDeviceResponse response = iotDAClient.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("修改华为云设备修改失败");
        }

        //2.修改本地数据库设备
        device.setDeviceName(dto.getDeviceName());
        this.updateDevice(device);
    }

    @Override
    public boolean deleteById(String iotId) {
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //删除华为云设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response;
        try {
            response = iotDAClient.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("删除华为云设备失败");
        }
        //根据主键删除本地数据库设备
        Long id = device.getId();
        return this.removeById(id);
    }
    /**
     * 查询产品详情(报警规则模块使用)
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        //1.参数校验
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("请提供正确的产品Key");
        }
        //2.创建华为云请求参数
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.withProductId(productKey);
        ShowProductResponse response;
        try {
            response = iotDAClient.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("获取设备详细信息失败");
        }
        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(serviceCapabilities);
    }

    /**
     * 查询健康数据
     *
     * @param dto
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusDTO dto) {
        Device device = this.getOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName())
                .eq(Device::getProductKey, dto.getProductKey()));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }

        // 2. 获取设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(device.getIotId());
        ShowDeviceShadowResponse response = iotDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备影子，调用失败");
        }

        List<DeviceShadowData> shadowList = response.getShadow();
        if (CollectionUtil.isEmpty(shadowList)) {
            return AjaxResult.success(Collections.emptyList());
        }

        // 3. 解析影子数据
        DeviceShadowProperties reported = shadowList.get(0).getReported();
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());

        // 4. 封装数据
        List<Map<String, Object>> propertyStatusInfo = new ArrayList<>();
        String eventTimeStr = reported.getEventTime();
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);

        jsonObject.forEach((key, value) -> {
            Map<String, Object> info = new HashMap<>();
            info.put("dataType", "int");
            info.put("identifier", key);
            info.put("name", key);
            /**
             * toEpochSecond(ZoneOffset.UTC)：
             * toEpochSecond() 是LocalDateTime的方法，用于计算该时间距离 时间戳起点（1970 年 1 月 1 日 00:00:00 UTC）的秒数。
             * 参数ZoneOffset.UTC表示计算时以 UTC 时区为基准（即使eventTime是上海时区时间，这里也会先转换为 UTC 时间再计算秒数）。
             * “带时区含义的本地时间” 转换为 “全球统一的毫秒级时间戳”，确保跨系统时间传递的准确性和一致性。
             */
            info.put("time", eventTime.toEpochSecond(ZoneOffset.UTC) * 1000); // 转换为毫秒时间戳
            info.put("unit", ""); // 根据实际情况设置
            info.put("value", value.toString());
            propertyStatusInfo.add(info);
        });

        // 5. 构建返回结果
        Map<String, Object> list = new HashMap<>();
        list.put("propertyStatusInfo", propertyStatusInfo);

        Map<String, Object> data = new HashMap<>();
        data.put("list", list);

        return AjaxResult.success(data);

    }

    /**
     * 按天统计查询指标数据
     */
    @Override
    public List<DeviceDataVO> queryDeviceDataByDay(String functionId, Long startTime, Long endTime, String iotId) {

        LocalDateTime start = LocalDateTimeUtil.of(startTime);
        LocalDateTime end = LocalDateTimeUtil.of(endTime);

        // 查询数据库获取实际数据
        List<DeviceDataVO> ddvList = deviceDataMapper.queryDeviceDataByDay(iotId, functionId, start, end);

        // 生成24小时的基础数据列表
        List<DeviceDataVO> resultList = dayData(start);

        // 如果数据库查询结果为空，直接返回全0的24小时列表
        if (CollectionUtil.isEmpty(ddvList)) {
            return resultList;
        }

        // 将数据库数据转换为Map
        Map<String, Double> dataMap = new HashMap<>();
        for (DeviceDataVO data : ddvList) {
            dataMap.put(data.getDateTime(), data.getDataValue());
        }

        // 用数据库数据填充24小时列表（有数据的替换，无数据的保持0.0）
        for (DeviceDataVO item : resultList) {
            String time = item.getDateTime();
            // 如果Map中有对应时间的数据，就替换掉初始的0.0
            if (dataMap.containsKey(time)) {
                item.setDataValue(dataMap.get(time));
            }
        }
        return resultList;
    }


//    todo :ai生成,在仔细观看一遍

    /**
     * 生成一天24小时的基础数据列表（每个小时初始值为0.0）
     *
     * @param startTime 起始时间（用于计算24小时的时间点）
     * @return 包含24个小时数据的列表
     */
    public static List<DeviceDataVO> dayData(LocalDateTime startTime) {
        List<DeviceDataVO> list = new ArrayList<>();
        // 循环生成24小时（0-23点）
        for (int i = 0; i < 24; i++) {
            // 计算当前的时间（起始时间 + i小时）
            LocalDateTime dataTime = startTime.plusHours(i);
            // 创建数据对象并设置时间和初始值
            DeviceDataVO dataVO = new DeviceDataVO();
            dataVO.setDateTime(LocalDateTimeUtil.format(dataTime, "HH:00")); // 格式化为"HH:00"形式
            dataVO.setDataValue(0.0); // 初始值为0.0
            list.add(dataVO);
        }
        return list;
    }

    /**
     * 按周查询指标数据
     *
     * @param functionId
     * @param startTime
     * @param endTime
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceDataVO> queryDeviceDataByWeek(String functionId, Long startTime, Long endTime, String iotId) {
        LocalDate start = LocalDateTimeUtil.of(startTime).toLocalDate();
        LocalDate end = LocalDateTimeUtil.of(endTime).toLocalDate();

        List<DeviceDataVO> ddvList = deviceDataMapper.queryDeviceDataByWeek(iotId, functionId, start, end);

//       生成七天的基础数据列表
        List<DeviceDataVO> resultList = weekData(start);
        if (CollectionUtil.isEmpty(ddvList)) {
            return resultList;
        }

        // 将数据库数据转换为Map
        Map<String, Double> dataMap = new HashMap<>();
        for (DeviceDataVO data : ddvList) {
            dataMap.put(data.getDateTime(), data.getDataValue());
        }

        // 用数据库数据填充24小时列表（有数据的替换，无数据的保持0.0）
        for (DeviceDataVO item : resultList) {
            String time = item.getDateTime();
            // 如果Map中有对应时间的数据，就替换掉初始的0.0
            if (dataMap.containsKey(time)) {
                item.setDataValue(dataMap.get(time));
            }
        }
        return resultList;


    }

    /*
    生成七天的空数据
     */
    public static List<DeviceDataVO> weekData(LocalDate start) {
        List<DeviceDataVO> list = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            LocalDate day = start.plusDays(i);
            DeviceDataVO ddv = new DeviceDataVO();
            ddv.setDateTime(LocalDateTimeUtil.format(day, "MM.dd"));
            ddv.setDataValue(0.0);
            list.add(ddv);
        }
        return list;
    }

}
